<template>
  <div class="register-card">
    <div class="register-warp">
      <div class = "register-welcome">
      <div class="register-title">注册</div>
      </div>
      <div class="form-body">
        <n-form :model="modelRef" ref="formRef" :rules="rules">
          <div class="register-form-input">
            <n-form-item path="name" label="昵称">
              <n-input
                color="#6777EF"
                background-color="#FDFDFF"
                placeholder="昵称"
                maxlength="30"
                v-model:value="modelRef.name"
              ></n-input>
            </n-form-item>
          </div>
          <div class="register-form-input">
            <n-form-item path="acc" label="账号">
              <n-input
                color="#6777EF"
                background-color="#FDFDFF"
                placeholder="邮箱"
                v-model:value="modelRef.acc"
              ></n-input>
            </n-form-item>
          </div>
          <div class="register-form-input">
            <n-form-item path="pwd" label="密码">
              <n-input
                color="#6777EF"
                background-color="#FDFDFF"
                placeholder="密码"
                v-model:value="modelRef.pwd"
                type="password"
                show-password-on="mousedown"
              ></n-input>
            </n-form-item>
          </div>
          <n-grid x-gap="4" :cols="17">
            <n-gi span="12">
              <div class="register-form-input-vercode">
                <n-form-item path="ver_code" label="验证码">
                  <n-input
                    color="#6777EF"
                    background-color="#FDFDFF"
                    placeholder="验证码"
                    v-model:value="modelRef.ver_code"
                    @keyup.enter.native="register"
                  ></n-input>
                </n-form-item>
              </div>
            </n-gi>
            <n-gi span="5">
              <div class="vercode-button">
                <div v-show="!isSent">
                  <n-button @click="getVerCode">发送验证码</n-button>
                </div>
                <n-button v-show="isSent" disabled>已发送&nbsp;{{ sendTime }}s</n-button>
              </div>
            </n-gi>
          </n-grid>
        </n-form>
        <div class="register-button">
          <n-button @click="register" color="#333333">注册</n-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { getCurrentInstance, ref, reactive } from "vue";
import { useMessage, NButton } from 'naive-ui';
import { useRouter } from 'vue-router';

// 引入路由
const router = useRouter()

//用于Message弹框
const message = useMessage()

// api访问代理
const { proxy } = getCurrentInstance() as any

const formRef = ref(null)
var isSent = ref(false)
var sendTime = ref(60)

const modelRef = reactive({
  acc: null,
  pwd: null,
  name: null,
  ver_code: null
})

const rules = {
  name: [
    {
      required: true,
      validator(rule: any, value: any) {
        if (!value) {
          console.log(value);
          return new Error('请输入姓名')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  acc: [
    {
      required: true,
      validator(rule: any, value: any) {
        if (!value) {
          console.log(value);
          return new Error('请输入账号(邮箱)')
        } else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
          return new Error('请输入邮箱')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  pwd: [
    {
      required: true,
      validator(rule: any, value: any) {
        if (!value) {
          console.log(value);
          return new Error('请输入密码')
        } else if (!/^(\w){6,20}$/.test(value)) {
          console.log(value);
          return new Error('密码应为6~20位，只包含字母、数字或下划线')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ],
  ver_code: [
    {
      required: true,
      validator(rule: any, value: any) {
        if (!value) {
          console.log(value);
          return new Error('请输入验证码')
        } else if (!/^(\w){6}$/.test(value)) {
          console.log(value);
          return new Error('验证码为6位')
        }
        return true
      },
      trigger: ['input', 'blur']
    }
  ]
}

const register = (() => {
  (formRef.value as any).validate((errors: any) => {
    if (!errors) {
      message.success('验证成功')
      proxy.$api.entry.register({ acc: modelRef.acc, pwd: modelRef.pwd, name: modelRef.name, ver_code: modelRef.ver_code }).then((result: any) => {
        if (result.success) {
          message.success("注册成功")
          router.push("/login")
        } else {
          message.error(result.msg)
        }
      }).catch(() => {
        message.error('未知错误')
      });
    } else {
      message.error('请检查填写信息')
    }
  })
})

const getVerCode = (() => {
  if (modelRef.acc == null) {
    message.warning("请输入账号(邮箱)");
  }
  else if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(modelRef.acc)) {
    message.warning("账号:请输入邮箱")
  }
  else {
    isSent.value = true;
    var verCodeTime = setInterval(() => {
      sendTime.value--;
    }, 1000);
    setTimeout(() => {
      clearInterval(verCodeTime);
      sendTime.value = 60;
      isSent.value = false;
    }, 60000);
    proxy.$api.entry.getVerCode({ acc: modelRef.acc }).then((result: any) => {
      if (result.success) {
        message.success("获取成功")
      } else {
        message.error(result.msg)
      }
    }).catch(() => {
      message.error('未知错误')
    });
  }
})
</script>

<style scoped>
.register-card{
  border-top: 3px solid #666;
  margin: 6% auto;
  width: 800px;
  border-radius: 5px;
  box-shadow: 0 8px 6px hsl(0deg 0% 78% / 50%);
  min-height: 515px;
}
.register-warp {
  margin: 3.5% auto;
  width: 43.3%;
  background: #fff;
}
.register-welcome{
  border-left: 5px solid #666;
  margin-right: 5px;
  padding-right: 10px;
  margin-bottom: 0;
}
.register-title {
  font-size: 26px;
  line-height: 28px;
  font-weight: bold;
  margin-left: 10px;
}
.form-body {
  margin-top: 7%;
}
.register-form-input {
  margin-top: 4px;
  margin-bottom: 8px;
  width: 100%;
}
.register-form-input-vercode {
  margin-top: 4px;
  margin-bottom: 8px;
  width: 100%;
}
.register-button {
  margin-left: 83.3%;
  outline-color: #333333;
}
.vercode-button {
  margin-top: 30px;
  margin-left: 0%;
}
</style>